package cn.zhx.Proxy.demo.CGLIBProxy;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ProxyFactory{

    private TrainStation target = new TrainStation();

    public TrainStation getProxyObject(){
        //创建Enhancer对象，类似于JDK动态代理的Proxy类，下一步就是设置几个参数
        Enhancer enhancer = new Enhancer();
        //设置父类的字节码对象
        enhancer.setSuperclass(target.getClass());
        //设置回调函数
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public TrainStation intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("收取一些费用");
                return (TrainStation) methodProxy.invokeSuper(o,objects);
            }
        });
        //创建代理对象
        TrainStation trainStation  = (TrainStation) enhancer.create();
        return trainStation;
    }

}
